/*
 *      Copyright (c) 2018-2028, Chill Zhuang All rights reserved.
 *
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions are met:
 *
 *  Redistributions of source code must retain the above copyright notice,
 *  this list of conditions and the following disclaimer.
 *  Redistributions in binary form must reproduce the above copyright
 *  notice, this list of conditions and the following disclaimer in the
 *  documentation and/or other materials provided with the distribution.
 *  Neither the name of the dreamlu.net developer nor the names of its
 *  contributors may be used to endorse or promote products derived from
 *  this software without specific prior written permission.
 *  Author: Chill 庄骞 (smallchill@163.com)
 */
package com.plian.system.service.sys.system.impl;

import com.plian.Tools.CollectionUtil;
import com.plian.Tools.DateUtil;
import com.plian.Tools.StringUtil;
import com.plian.system.common.status.CustomCode;
import com.plian.system.constant.sys.FormTypeConstant;
import com.plian.system.dto.sys.SystemRecordDTO;
import com.plian.system.entity.sys.SystemRecord;
import com.plian.system.mapper.sys.SystemRecordMapper;
import com.plian.system.model.CommonCode;
import com.plian.system.model.R;
import com.plian.system.mybatis.base.BaseServiceImpl;
import com.plian.system.service.sys.file.FileService;
import com.plian.system.service.sys.system.ISystemRecordService;
import com.plian.system.vo.report.HeaderVO;
import com.plian.system.vo.report.ReportReturnVO;
import com.plian.system.vo.report.ReportVO;
import com.plian.system.vo.sys.SystemRecordVO;
import com.plian.system.wrapper.util.WrapperUtil;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Optional;

/**
 * 国资委制度 服务实现类
 *
 * @author jianglei
 * @since 2019-10-23
 */
@Slf4j
@Service
@AllArgsConstructor
public class SystemRecordServiceImpl extends BaseServiceImpl<SystemRecordMapper, SystemRecord> implements ISystemRecordService {

	private FileService fileService;

	private WrapperUtil wrapperUtil;

	@Override
	public boolean saveOrUpdate(SystemRecord systemRecord) {
		boolean flag = false;
		if (systemRecord.getId() == null){
			flag = true;
			systemRecord.setFormType(String.valueOf(FormTypeConstant.SYS_SYSTEM));
		}
		boolean result = super.saveOrUpdate(systemRecord);
		if (flag){
			fileService.saveAll(String.valueOf(systemRecord.getId()), systemRecord.getDocList());
		}else {
			fileService.edit(String.valueOf(systemRecord.getId()), systemRecord.getDocList());
		}
		return result;
	}

	@Override
	public R failure(Long id, String failureTime) {
		SystemRecord systemRecord = getById(id);
		if (!Optional.ofNullable(systemRecord).isPresent()){
			return new R(CustomCode.builder().message("该制度不存在").code(1999).success(false).build());
		}
		if (Optional.ofNullable(systemRecord.getSystemStatus()).isPresent() && systemRecord.getSystemStatus() != 1){
			return new R(CustomCode.builder().message("该制度已失效").code(1999).success(false).build());
		}

		systemRecord.setStatus(3);
		Date failureDate = null;
		if (StringUtil.isNotBlank(failureTime)){
			failureDate = DateUtil.parse(failureTime, DateUtil.PATTERN_DATE);
			long now = DateUtil.parse(DateUtil.format(DateUtil.now(), DateUtil.PATTERN_DATE), DateUtil.PATTERN_DATE).getTime();
			if (failureDate.getTime() <= now){
				systemRecord.setSystemStatus(2);
			}
		}
		systemRecord.setFailureTime(failureDate);
		return  updateById(systemRecord) ? new R(CommonCode.SUCCESS) : new R(CommonCode.FAIL);
	}

	@Override
	public ReportReturnVO summaryList(SystemRecordDTO systemRecordDTO) {
		List<SystemRecordVO> data = baseMapper.summaryList(systemRecordDTO);
		List<SystemRecordVO> results = new ArrayList<>();
		if (CollectionUtil.isNotEmpty(data)){
			int totalCount = 0;
			int subtotalCount = 0;
			String departmentCode = "";

			for (int i = 0; i < data.size(); i++){
				SystemRecordVO result = data.get(i);
				if (StringUtil.isNotBlank(departmentCode) && !departmentCode.equals(result.getDepartmentCode())){
					SystemRecordVO subtotal = new SystemRecordVO();
					subtotal.setDepartmentName("小计：" + subtotalCount);
					results.add(subtotal);
					subtotalCount = 1;
				}else {
					subtotalCount++;
				}
				departmentCode = result.getDepartmentCode();
				totalCount++;
				result.setSystemStatusStr(wrapperUtil.systemStatus(result.getSystemStatus()));
				results.add(result);
				if (i == data.size() - 1){
					SystemRecordVO subtotal = new SystemRecordVO();
					subtotal.setDepartmentName("小计：" + subtotalCount);
					results.add(subtotal);
				}
			}
			SystemRecordVO end = new SystemRecordVO();
			end.setDepartmentName("合计：" + totalCount);
			results.add(end);
		}

		ReportReturnVO reportReturnVO = new ReportReturnVO();
		ReportVO reportVO = new ReportVO();
		reportVO
				.addHeader(HeaderVO.builder().key("systemName").title("制度名称").build())
				.addHeader(HeaderVO.builder().key("departmentName").title("归口部门（国资委）").build())
				.addHeader(HeaderVO.builder().key("systemTypeName").title("制度类型").build())
				.addHeader(HeaderVO.builder().key("instructions").title("说明").build())
				.addHeader(HeaderVO.builder().key("orgName").title("归属集团").build())
				.addHeader(HeaderVO.builder().key("fillingTime").title("填报时间").build())
				.addHeader(HeaderVO.builder().key("systemStatusStr").title("状态").build())
				.addHeader(HeaderVO.builder().key("effectTime").title("开始生效时间").build())
				.addHeader(HeaderVO.builder().key("failureTime").title("失效时间").build());
		reportVO.setData(results);
		reportReturnVO.setGrids(reportVO);
		return reportReturnVO;
	}
}
